package com.lagou.config;
/*
 * PackageName: com.lagou.config
 * ClassName:
 * Author:   zhang
 * Date:     Created in 2020/9/26
 * Description:
 * History:
 * <author>        <time>             <version>          <desc>
 * 作者姓名         修改时间            版本号              描述
 * zhang           2020/9/26      1.0
 */

import com.lagou.enums.SqlTypeEnum;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * Title:
 * Project: IPersistence_test
 *
 * @author ZhangKe
 * Created on 2020/9/26
 */
public class XMLMapperBuilder {

    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectList = rootElement.selectNodes("//select");
        parseSqlStatement(namespace,selectList,SqlTypeEnum.SELECT);

        List<Element> insertList = rootElement.selectNodes("//insert");
        parseSqlStatement(namespace,insertList,SqlTypeEnum.INSERT);

        List<Element> deleteList = rootElement.selectNodes("//delete");
        parseSqlStatement(namespace,deleteList,SqlTypeEnum.DELETE);

        List<Element> updateList = rootElement.selectNodes("//update");
        parseSqlStatement(namespace,updateList,SqlTypeEnum.UPDATE);


    }

    public void parseSqlStatement(String namespace, List<Element> list,SqlTypeEnum sqlTypeEnum){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlType(sqlTypeEnum.getName());
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }
}
